package com.feige.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feige.constant.Constants;
import com.feige.entity.SecurityUser;
import com.feige.pojo.Dept;
import com.feige.pojo.vo.BaseDeptVo;
import com.feige.pojo.vo.DeptVo;
import com.feige.result.AjaxResult;
import com.feige.service.DeptService;
import com.feige.utils.common.Admin;
import com.feige.utils.common.BeanUtils;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import com.feige.utils.string.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author feige
 * @since 2020-10-23
 */
@Api(tags = "部门类")
@RestController
@RequestMapping("/admin/dept")
public class DeptController {

    @Resource
    private DeptService deptService;

    @Resource
    private RedisUtils redisUtils;

    @PreAuthorize("@ss.hasPerm('user:dept:list')")
    @ApiOperation(value = "获取所有部门,转化为树形结构")
    @GetMapping("/get-tree-all")
    public AjaxResult queryAllDept(){
        List<Dept> depts = deptService.queryAllDept();
        return AjaxResult.success(depts);
    }

    @ApiOperation(value = "获取用户管理部门的下拉列表,转化为树形结构")
    @GetMapping("/get-tree")
    public AjaxResult queryAllDeptTree(HttpServletRequest req){
        String token = req.getHeader(Constants.TOKEN_KEY);
        String num = JwtUtils.getNumFromToken(token);
        List<BaseDeptVo> depts;
        if (Admin.isAdmin(num)){
            depts = deptService.queryAllDeptTree(null);
        }else {
            String key = JwtUtils.getUsernameAndNumFromToken(token);
            SecurityUser securityUser = (SecurityUser) redisUtils.get(Constants.LOGIN_USER_KEY + key);
            if (StringUtils.isNotNull(securityUser)){
                String manageDeptIds = securityUser.getCurrentUser().getManageDeptIds();
                if (!StringUtils.isEmpty(manageDeptIds)) {
                    String[] split = manageDeptIds.split(",");
                    List<Long> ids = Arrays.stream(split).map(Long::parseLong).collect(Collectors.toList());
                    depts = deptService.queryAllDeptTree(ids);
                }else {
                    depts = new ArrayList<>();
                }
            }else {
                depts = new ArrayList<>();
            }
        }
        return AjaxResult.success(depts);
    }

    @PreAuthorize("@ss.hasPerm('user:dept:list')")
    @ApiOperation(value = "获取所有部门")
    @GetMapping("/get-list")
    public AjaxResult getAll(String deptName,Integer status){
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(deptName)){
            wrapper.like("dept_name",deptName);
        }
        if (status != null){
            wrapper.eq("status",status);
        }
        List<Dept> depts = deptService.list(wrapper);
        List<DeptVo> deptVos = BeanUtils.convertList2List(depts, DeptVo.class);
        return AjaxResult.success(deptVos);
    }

    @PreAuthorize("@ss.hasPerm('user:dept:list')")
    @ApiOperation(value = "根据部门ID获取对应的部门")
    @GetMapping("/get-dept/{id}")
    public AjaxResult getDeptById(@PathVariable Long id){
        Dept dept =deptService.getById(id);
        return AjaxResult.success(dept);
    }

    @PreAuthorize("@ss.hasPerm('user:dept:list')")
    @ApiOperation(value = "查询部门列表,排除该部门下的所有子部门")
    @GetMapping("/get/exclude/{id}")
    public AjaxResult listDeptExcludeChild(@PathVariable Long id){
        List<Dept> dept = deptService.listDeptExcludeChild(id);
        return AjaxResult.success(dept);
    }

    @PreAuthorize("@ss.hasPerm('user:dept:add')")
    @ApiOperation(value = "新增部门")
    @PostMapping("/save")
    public AjaxResult save(@Validated @RequestBody Dept dept){
        int save = deptService.saveDept(dept);
        if (save > 0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:dept:edit')")
    @ApiOperation(value = "修改部门")
    @PutMapping("/update")
    public AjaxResult update(@Validated @RequestBody Dept dept){
        int update = deptService.updateDeptById(dept);
        if (update > 0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:dept:delete')")
    @ApiOperation(value = "级联删除部门")
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id){
        boolean delete = deptService.removeById(id);
        if (delete){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

}

